package cn.haoxsf.app.component;

import cn.haoxsf.app.common.api.enums.SystemExceptionEnum;
import cn.haoxsf.app.common.api.enums.UserExceptionEnum;
import cn.haoxsf.app.common.util.JwtTokenUtil;
import cn.haoxsf.app.common.util.ToolUtil;
import cn.haoxsf.app.system.dto.LoginUser;
import cn.haoxsf.app.system.dto.MemberDetailsService;
import cn.haoxsf.app.system.service.IRedisService;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: app
 * @description: JWT登录授权过滤器
 * @author: Ele qvbanfm@qq.com
 * @create: 2020-01-06 13:23
 **/
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private MemberDetailsService memberDetailsService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length()).trim();// The part after "Bearer "
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                LoginUser userDetails = memberDetailsService.loadUserByUsername(username);
                //  redis是否过期 用户注销 和用户key 缓存
                if(ToolUtil.isEmpty(redisService.getString(userDetails.getId().toString()+":"+userDetails.getUsername()))){
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json");
                    response.getWriter().write(JSONUtil.toJsonStr(SystemExceptionEnum.UNAUTHORIZED));
                    return;
                }
                if (!userDetails.isEnabled()) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/json");
                    response.getWriter().write(JSONUtil.toJsonStr(UserExceptionEnum.IS_ACCOUNT_LOCKED));
                    return;
                }
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
